package netWork.练习1_聊天室.多客户端实现;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.util.Scanner;

/**
 * @Package netWork.练习1_聊天室.多客户端实现
 * @Author shimmer
 * @Date 2020/8/4 8:22
 * @TODO
 */
public class Client3 {
    Socket server;
    Scanner scanner;
    String msg;
    DataInputStream is;
    DataOutputStream os;
    boolean over=false;// 退出标志

    public Client3() {
        try {
            this.server = new Socket("127.0.0.1", 8888);
            this.scanner = new Scanner(System.in);
            new WriteThread().start();// 开启发送线程
            is = new DataInputStream(server.getInputStream());
            while (true) {
                msg = is.readUTF();// 阻塞读取
                System.out.println(msg);
                if (over) {
                    break;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            new CloseUtil(is, os, scanner, server).close();
        }
    }

    public static void main(String[] args) {
        new Client3();
    }

    // 写线程
    class WriteThread extends Thread {
        @Override
        public void run() {
            try {
                os = new DataOutputStream(server.getOutputStream());
                while (true) {
                    msg = scanner.nextLine();// scanner.nextLine()阻塞等待输入
                    os.writeUTF(msg);
                    if ("q".equals(msg)) {
                        over=true;
                        break;
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
